package org.example.managementsystem.service;

import org.example.managementsystem.model.MaterialPurchase;
import org.example.managementsystem.repository.MaterialPurchaseDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 物料采购服务
 */
@Service
public class MaterialPurchaseService {

    private final MaterialPurchaseDao materialPurchaseDao;

    @Autowired
    public MaterialPurchaseService(MaterialPurchaseDao materialPurchaseDao) {
        this.materialPurchaseDao = materialPurchaseDao;
    }

    /**
     * 提交采购申请
     */
    public MaterialPurchase submitPurchaseApplication(MaterialPurchase purchase) {
        // 设置申请状态为待审批
        purchase.setIsApproved(false);

        // 设置入库日期
        if (purchase.getStorageDate() == null) {
            purchase.setStorageDate(new Date(System.currentTimeMillis()));
        }

        // 保存采购申请
        Long id = materialPurchaseDao.insertMaterialPurchase(purchase);
        purchase.setPurchaseId(id);

        return purchase;
    }

    /**
     * 获取待审批的采购申请列表
     */
    public List<MaterialPurchase> getPendingApprovals() {
        return materialPurchaseDao.getPendingApprovals();
    }

    /**
     * 提交审批决定
     */
    public MaterialPurchase submitApproval(Long purchaseId, boolean isApproved, String reason) {
        // 获取采购申请
        MaterialPurchase purchase = materialPurchaseDao.getMaterialPurchaseById(purchaseId);
        if (purchase == null) {
            throw new RuntimeException("采购申请不存在");
        }

        // 检查是否已经审批过
        if (purchase.getApprovalStatus()) {
            throw new RuntimeException("该申请已审批，不能重复审批");
        }

        // 插入或更新审批记录
        materialPurchaseDao.insertOrUpdateApproval(purchaseId, isApproved, reason);
        
        // 更新申请表的审批状态
        materialPurchaseDao.updateApplicationApprovalStatus(purchaseId, isApproved);

        // 重新获取更新后的采购申请
        return materialPurchaseDao.getMaterialPurchaseById(purchaseId);
    }

    /**
     * 审批采购申请（保留原有方法）
     */
    public MaterialPurchase approvePurchaseApplication(Long purchaseId, boolean isApproved,
                                                       String approverId, String approverName, String description) {
        // 获取采购申请
        MaterialPurchase purchase = materialPurchaseDao.getMaterialPurchaseById(purchaseId);
        if (purchase == null) {
            throw new RuntimeException("采购申请不存在");
        }

        // 只有未审批的申请才能审批
        if (purchase.getApprovalStatus() != null && purchase.getApprovalStatus()) {
            throw new RuntimeException("该申请已审批，不能重复审批");
        }

        // 更新审批状态
        materialPurchaseDao.updatePurchaseApprovalStatus(purchaseId, isApproved, description);

        // 重新获取更新后的采购申请
        return materialPurchaseDao.getMaterialPurchaseById(purchaseId);
    }

    /**
     * 修改采购申请
     */
    public MaterialPurchase updatePurchaseApplication(MaterialPurchase purchase) {
        // 获取原采购申请
        MaterialPurchase originalPurchase = materialPurchaseDao.getMaterialPurchaseById(purchase.getPurchaseId());
        if (originalPurchase == null) {
            throw new RuntimeException("采购申请不存在");
        }

        // 只有未审批的申请才能修改
        if (originalPurchase.getApprovalStatus() != null && originalPurchase.getApprovalStatus()) {
            throw new RuntimeException("已审批的申请不能修改");
        }

        // 更新采购申请
        materialPurchaseDao.updateMaterialPurchase(purchase);

        return purchase;
    }

    /**
     * 撤销采购申请
     */
    public void cancelPurchaseApplication(Long purchaseId) {
        // 获取采购申请
        MaterialPurchase purchase = materialPurchaseDao.getMaterialPurchaseById(purchaseId);
        if (purchase == null) {
            throw new RuntimeException("采购申请不存在");
        }

        // 只有未审批的申请才能撤销
        if (purchase.getApprovalStatus() != null && purchase.getApprovalStatus()) {
            throw new RuntimeException("已审批的申请不能撤销");
        }

        // 删除采购申请
        materialPurchaseDao.deleteMaterialPurchase(purchaseId);
    }

    /**
     * 完成采购
     */
    public MaterialPurchase completePurchase(Long purchaseId, String purchaseDetails) {
        // 获取采购申请
        MaterialPurchase purchase = materialPurchaseDao.getMaterialPurchaseById(purchaseId);
        if (purchase == null) {
            throw new RuntimeException("采购申请不存在");
        }

        // 只有已批准的申请才能完成采购
        if (!Boolean.TRUE.equals(purchase.getApprovalStatus())) {
            throw new RuntimeException("只有已批准的申请才能完成采购");
        }

        // 更新采购详情和状态
        purchase.setPurchaseDesc(purchaseDetails);
        purchase.setIsApproved(true);

        materialPurchaseDao.updateMaterialPurchase(purchase);

        return purchase;
    }

    /**
     * 获取所有采购申请
     */
    public List<MaterialPurchase> getAllPurchaseApplications() {
        return materialPurchaseDao.getAllMaterialPurchases();
    }

    /**
     * 获取指定申请人的采购申请
     */
    public List<MaterialPurchase> getPurchaseApplicationsByApplicant(String applicantJobNumber) {
        return materialPurchaseDao.getMaterialPurchasesByApplicant(applicantJobNumber);
    }

    /**
     * 获取物料采购统计数据
     */
    public Map<String, Object> getPurchaseStatistics(LocalDateTime startTime, LocalDateTime endTime, String departmentId) {
        Map<String, Object> statistics = new HashMap<>();

        // 查询条件下的所有采购申请
        List<MaterialPurchase> purchases = materialPurchaseDao.getAllMaterialPurchases();

        // 如果指定了时间范围，过滤时间范围
        if (startTime != null && endTime != null) {
            // 假设这里有根据时间过滤的方法
            // purchases = filterByTime(purchases, startTime, endTime);
        }

        // 如果指定了部门，过滤部门数据
        if (departmentId != null && !departmentId.isEmpty()) {
            purchases = purchases.stream()
                    .filter(p -> departmentId.equals(p.getApplicantJobNumber()))
                    .collect(Collectors.toList());
        }

        // 统计批准和未批准数量
        long approvedCount = purchases.stream()
                .filter(p -> Boolean.TRUE.equals(p.getApprovalStatus()))
                .count();
        long unapprovedCount = purchases.size() - approvedCount;

        statistics.put("approvedCount", approvedCount);
        statistics.put("unapprovedCount", unapprovedCount);

        // 统计各物料类型采购数量
        Map<String, Long> typeCount = purchases.stream()
                .collect(Collectors.groupingBy(
                        MaterialPurchase::getMaterialType,
                        Collectors.counting()
                ));
        statistics.put("typeCount", typeCount);

        return statistics;
    }

    /**
     * 生成采购单号
     */
    private String generatePurchaseNumber() {
        // 格式：PO + 年月日 + 6位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomStr = UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        return "PO" + dateStr + randomStr;
    }

    public MaterialPurchase getPurchaseApplicationById(Long id) {
        return materialPurchaseDao.getMaterialPurchaseById(id);
    }

    public void deletePurchaseApplication(Long id) {
        materialPurchaseDao.deleteById(id);
    }

    public void createMaterialPurchase(MaterialPurchase purchaseMaterial) {

        // 设置默认值（如创建时间、更新时间等）
        if (purchaseMaterial.getStorageDate() == null) {
            purchaseMaterial.setStorageDate(new Date(System.currentTimeMillis()));
        }

        // 生成采购单号（如果未提供）
        // 注：如果业务需要自动生成采购单号，可在此添加逻辑
        // String purchaseNumber = generatePurchaseNumber();
        // purchaseMaterial.setPurchaseNumber(purchaseNumber);

        // 调用DAO层插入数据
        Long id = materialPurchaseDao.insertMaterialPurchase(purchaseMaterial);
        purchaseMaterial.setPurchaseId(id);
    }
}